Cuestionario Ampliado del Censo de Población y Vivienda 2020

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Personas_Censo 2020.SAV")

save(data, 
      file = paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

load(paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

mydata <- data %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES15, 
                  ENT_PAIS_NAC, ENT_PAIS_TRAB, MUN_TRAB, CVE_MUN_TRABAJO, 
                  ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, EDAD, SEXO, AFRODES, HLENGUA, QDIALECT_INALI, 
                  PERTE_INDIGENA, ALFABET, CAUSA_MIG, SITUA_CONYUGAL, HIJOS_NAC_VIVOS, 
                  CONACT, OCUPACION_C, SITTRA, VACACIONES, SERVICIO_MEDICO, INCAP_SUELDO, INGTRMEN, 
                  ACTIVIDADES_C, TIE_TRASLADO_TRAB, MED_TRASLADO_TRAB1, MED_TRASLADO_TRAB2, MED_TRASLADO_TRAB3,
                  ASISTEN, NIVACAD, ESCOLARI, ESCOACUM,  NOMCAR_C, TIE_TRASLADO_ESCU, 
                  MED_TRASLADO_ESC1, MED_TRASLADO_ESC2, MED_TRASLADO_ESC3,
                  FACTOR, ESTRATO, UPM)

Zonas Metropolitanas 2020

Se anexa la base de datos de las Zonas Metropolitanas 2020 a la base orginal

ZM_2020 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2020.xlsx"), 
                      startRow = 7, 
                       skipEmptyRows = TRUE) %>%
            select(CVE_ZM, NOM_ZM, CVE_ENT, NOM_ENT, CVE_MUN, NOM_MUN, MC, CF) %>%
             mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                    CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Se asignan las claves de las zonas metropolitanas de acuerdo a las diferentes variables de interes: - Residencia hace 5 años - Laboral - Estudiantil - Nacimiento

mydata <- mydata %>%
           rename("CVE_MUN_RES" = "CVE_MUN_RES15") %>%
          # Zonas Metropolitanas por residenicia
            left_join(., ZM_2020 %>% select(-CVE_ENT), by = c("CVE_MUN")) %>%
            # Zonas Metropolitanas en el lugar de residencia hace 5 años
             left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>% 
                           rename("CVE_ZM_RES" = "CVE_ZM",
                                  "ZM_RES" = "NOM_ZM",
                                  "MC_RES" = "MC",
                                  "CF_RES" = "CF"), by = c("CVE_MUN_RES" = "CVE_MUN")) %>%
             # Zonas Metropolitanas en el lugar de trabajo
              left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>%
                            rename("CVE_ZM_TRABAJO" = "CVE_ZM",
                                   "ZM_TRABAJO" = "NOM_ZM",
                                   "MC_TRABAJO" = "MC",
                                   "CF_TRABAJO" = "CF"), by = c("CVE_MUN_TRABAJO" = "CVE_MUN")) %>%
             # Zonas Metropolitanas en el lugar de estudio
               left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>%
                             rename("CVE_ZM_ASI" = "CVE_ZM",
                                    "ZM_ASI" = "NOM_ZM",
                                    "MC_ASI" = "MC",
                                    "CF_ASI" = "CF"), by = c("CVE_MUN_ASI" = "CVE_MUN"))

save(mydata, file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2020.RData"))          

✔️A partir de aquí se pueden correr los códidos 👇. Se carga el archivo Migracion por Zonas Metropolitanas_2020.RData.

load(file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2020.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, 
                  EDAD, CVE_ZM, NOM_ZM, NOM_ENT, NOM_MUN, MC, CF, CVE_ZM_RES, ZM_RES, 
                  MC_RES, CF_RES, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1)  %>%
             mutate(NOM_ENT = as.factor(.$CVE_ENT)) %>%
              ungroup()

# Se vuelve a cargar la base de datos para fines practicos
ZM_2020 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2020.xlsx"), 
                      startRow = 7, 
                       skipEmptyRows = TRUE) %>%
            mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                   CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Entidades y Municipios

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios, pero es importante hacer notar que tres municipios no entraron el muestreo del Cuestionario Ampliado.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)
nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")
est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2020.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()
#saveRDS(MUN, file = paste0(here::here(), "/Bases/municipios_2020.RDS"))

# Claves de las zonas metropolitanas
zm <- sjlabelled::get_labels(mydata$CVE_ZM)[-2]
nom_zm <- sjlabelled::get_labels(mydata$NOM_ZM)[-2]

Migración reciente

Migración interna

Matrices

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, CVE_ZM, MC, CF, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2020 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_municipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 20)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Reciente")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel municipal, 2015 - 2020

Matriz de migración reciente 2015 - 2020
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 811844 835 491 0 1335 440 550 177 177 571 655 183 426 0 120 59 0 0 0 177 0 0 0 0 0 0 0 0 0
001002 330 44223 10 5 28 15 33 0 72 56 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 139 0 50577 0 20 0 21 0 0 0 0 4 6 6 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 75 3 0 14634 16 3 80 0 18 0 2 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0
001005 3166 199 19 34 107678 98 46 30 89 46 201 0 9 0 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 199 5 36 5 177 40671 234 2 50 0 358 0 4 0 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 238 13 25 135 33 93 49027 26 82 0 61 0 0 0 28 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 41 2 2 0 20 28 12 8174 35 0 8 4 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 75 31 0 15 0 73 153 0 19446 0 41 0 8 3 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 219 18 0 0 5 0 2 0 0 17365 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2240 203 160 2 536 523 21 92 67 5 46088 0 0 0 0 156 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 14 0 0 0 0 0 0 0 0 376054 1737 214 2213 115 0 449 1032 701 245 56 0 0 0 0 0 0 0
002002 174 67 0 0 0 0 0 0 0 0 0 1139 929519 755 1677 347 0 0 48 79 150 0 0 0 0 0 0 0 0
002003 70 0 0 0 0 0 0 0 0 0 0 52 865 83911 1214 49 0 25 0 0 97 0 0 0 0 0 0 0 0
002004 165 0 0 0 0 0 0 0 0 0 0 1433 2600 1716 1546345 2894 0 0 648 965 913 0 0 165 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 176 307 149 1299 101415 0 0 0 65 25 0 0 24 37 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 82 0 267 0 91557 0 460 70 150 66 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 39 59 0 28 0 0 64658 234 496 297 137 0 8 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 786 225 11 119 18 0 135 54515 173 43 22 0 0 0 0 0 0 0
003003 20 0 0 0 0 0 0 0 0 0 0 494 225 0 643 0 0 1741 1082 249997 2700 348 0 0 0 0 0 0 0
003008 119 0 0 0 0 0 0 0 0 0 0 272 174 26 426 221 0 237 287 981 260221 185 0 76 0 28 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 26 12 0 63 0 0 98 26 169 12 15609 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52125 284 96 137 122 83 0
004002 17 0 0 0 0 0 0 0 0 0 0 40 0 0 51 0 0 0 49 0 0 0 182 257197 1080 736 120 494 54
004003 32 0 0 0 0 0 0 0 0 0 0 0 0 0 11 0 0 0 0 0 0 0 81 525 210329 452 0 0 33
004004 0 0 0 0 0 0 0 0 0 0 0 36 0 0 7 0 0 0 0 0 0 0 0 217 469 67521 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 20 139 9 56 28556 26 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92 0 7 5 36662 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 33 2 0 0 7728
004008 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 5 139 12 2 22 5 2
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})
################################################################################
################################## Filtro ######################################
Inmigrantes_function <- function(ZM, Migrantes){
                          lapply(1:length(ZM), function(x){
                                    Migrantes %>%
                                     as.data.frame() %>%
                                      tibble::rownames_to_column(var = "rn") %>% 
                                       melt(., id.vars = "rn", variable.name = "cn") %>%
                                        mutate_if(is.factor, as.character) %>%
                                         mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>%
                                          filter(value > 0) %>%
                                           group_by(rn) %>% 
                                            summarise(Inmigrantes = sum(value, na.rm = TRUE)) 
})
}
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes_function <- function(ZM, Migrantes){
                          lapply(1:length(ZM), function(x){
                                    Migrantes %>%
                                     as.data.frame() %>%
                                      tibble::rownames_to_column(var = "rn") %>% 
                                       melt(., id.vars = "rn", variable.name = "cn") %>%
                                        mutate_if(is.factor, as.character) %>%
                                         mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>%
                                          filter(value > 0) %>%
                                           group_by(cn) %>% 
                                            summarise(Emigrantes = sum(value, na.rm = TRUE)) 
})
}
Emigrantes <- Emigrantes_function(ZM, Migrantes)


################################## Filtro ######################################
#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = tabla_municipios,
  #              filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    # filtro de municipios de la ZM
                                      filtro  <- Inmigrantes[[x]] %>%
                                                  full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                    mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                     filter(value > filtro_mig[x]) %>%   ## Cambia el filtro de los municipios de la Zonas Metropolitanas
                                                      pull(rn)
                                      
                                    # filtro de estados
                                     filtro_est <- Inmigrantes[[x]] %>%
                                                    full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                     filter(rn %nin% ZM[[x]]) %>%
                                                      mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                       mutate(rn = substr(.$rn, 1, 3)) %>%
                                                        group_by(rn) %>%
                                                         summarise(value = sum(value)) %>%
                                                          filter(value >= filtro_out[x]) %>% 
                                                           pull(rn)
                                     
                                     Migrantes %>%
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "rn") %>% 
                                        melt(., id.vars = "rn", variable.name = "cn") %>%
                                         mutate_if(is.factor, as.character) %>%
                                          filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                           mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                            mutate(rn = case_when(.$rn %in% ZM[[x]] & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                                                  .$rn %in% ZM[[x]] & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZM"), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                                                   cn = case_when(.$cn %in% ZM[[x]] & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                                                  .$cn %in% ZM[[x]] & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZM"), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                                            filter(value > 0) %>%
                                             dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                              column_to_rownames(., var = "rn") 
  }
)

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm =  TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#                              }
#})

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Tabla MR5a a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Tabla MR5a a nivel municipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Tabla MR5a a nivel municipal.RDS"))

#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM.pdf"
 
## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family <- "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Gráfico Sankey

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 25)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 3) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)


################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

################################################################################

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    ZM <- ZM_2020 %>%
                                           select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                            filter(CVE_ZM %in% ZM_CF[x])  %>%
                                             mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                              pull(NOM_MUN)
                                    
                                    # filtro de municipios metropolitanos
                                     filtro <- filtro %>%
                                      filter(rn %in% ZM) %>%
                                       filter(value < 1000) %>%
                                        pull(rn)
                                     
                                    # filtro de estados
                                     filtro_rn  <- filtro_est %>%
                                                    mutate(value = ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>%
                                                     mutate(rn = substr(.$rn, 1, 3)) %>%
                                                      group_by(rn) %>%
                                                       summarise(Inm = sum(value, na.rm = TRUE))
              
                                     filtro_cn  <- filtro_est %>%
                                                    mutate(value =  ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>% 
                                                     mutate(cn = substr(.$cn, 1, 3)) %>%
                                                      group_by(cn) %>%
                                                       summarise(Emg = sum(value, na.rm = TRUE))
              
                                     filtro_estados <- filtro_rn %>%
                                                        full_join(., filtro_cn, by = c("rn" = "cn")) %>%
                                                         mutate(value = sum_row(.$Inm, .$Emg, na.rm = TRUE)) %>%
                                                          filter(value > 5000) %>%
                                                           pull(rn)
                                     
                                     tabla %>%
                                      mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), .$value, 0)) %>%
                                       mutate(rn = case_when(.$rn %in% ZM & .$rn %nin% filtro ~ .$rn,
                                                             .$rn %in% ZM & .$rn %in% filtro ~ paste(substr(.$rn, 1, 3), "Municipios ZM"),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %nin% filtro_estados ~ "Otros estados"),
                                              cn = case_when(.$cn %in% ZM & .$cn %nin% filtro ~ .$cn,
                                                             .$cn %in% ZM & .$cn %in% filtro ~ paste(substr(.$cn, 1, 3), "Municipios ZM"),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %nin% filtro_estados ~ "Otros estados")) %>%
                                        dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE, fill = 0) %>%
                                         column_to_rownames(., var = "rn") 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(),"/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/GSankey de MR5a desagregado por ZM_Absolutos.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 40000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 25000) %>% 
                      pull(rn)

################################################################################
tabla1 <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 50),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 50),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 50),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 50),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0) %>%
                  dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                   column_to_rownames(., var = "rn") 
cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a de ZMVM.pdf"), 
          width = 7,
          height = 7, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(1.5, 4))

# Paleta de colores
groupColors <- setNames(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 0.2, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(7),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(5),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

dev.off()
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 30000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 25000) %>% 
                      pull(rn)

################################################################################
tabla <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$rn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$cn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0)  


tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a de ZMVM a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a de ZMVM_grupos.pdf"), 
          width = 10, height = 10, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(0, 4))

# Paleta de colores
groupColors <- setNames(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 1, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(9),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(7),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

highlight.sector(grupo1, 
                 track.index = 1, 
                 col = groupColors[1], 
                 text = "Ciudad de México", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), niceFacing = TRUE)

highlight.sector(grupo2, 
                 track.index = 1, 
                 col = groupColors[15], 
                 text = "México", 
                 cex = 1.5, 
                 text.col = "white",
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo3, 
                 track.index = 1, 
                 col = groupColors[20], 
                 text = "Hidalgo", 
                 cex = 1, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo4, 
                 track.index = 1, 
                 col = groupColors[30], 
                 text = "Otro municipios", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

dev.off()

Etiquetas

etiquetas  <- lapply(1, function(x){
                        orden <- str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)
                        p <-  tabla1 %>% 
                               as.data.frame() %>%
                                tibble::rownames_to_column(var = "rn") %>%
                                 melt(., id.vars = "rn", variable.name = "cn") %>%
                                  as.data.frame() %>% 
                                   mutate(rn = str_wrap(.$rn, 100),
                                          cn = str_wrap(.$cn, 100)) %>%
                                    ggplot() + 
                                     geom_bar(aes(x = value, fill = as.character(rn, orden)))  + 
                                      geom_bar(aes(x = value, fill = as.character(cn, orden)))  + 
                                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                             text = element_text(family = "Montserrat Medium"),
                                             axis.text = element_blank(),
                                             axis.title = element_blank(),
                                             strip.text = element_text(size = 9, face = "bold", family = "Montserrat Medium"),  
                                             legend.key.size = unit(0.4, "cm"), 
                                             legend.spacing.y = unit(0.4, "cm"),
                                             legend.text = element_text(size = 7, family = "Montserrat Medium"),
                                             legend.title = element_text(size = 8 , family = "Montserrat Medium")) + 
                                       scale_fill_manual(values = colorRampPalette(paleta)(max(ncol(tabla1), nrow(tabla1)))) + 
                                         guides(fill = guide_legend(ncol = 1)) + 
                                        guides(fill = guide_legend(ncol = 1)) + 
                                         labs(fill = "ZM del Valle de México",
                                          color = "ZM del Valle de México")
                         leg <- get_legend(p)
                         as_ggplot(leg)
 })

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas ZMVM a nivel municipal.pdf"), 
          width = 7, height = 9, 
          fallback_resolution = 400,
          family = "montserrat", onefile = TRUE)
for(i in 1){
  print(etiquetas[i])
}
dev.off()
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value < 50000) %>% 
                pull(rn)

### filtro de estados
filtro_rn <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & .$rn %in% ZM |.$cn %in% ZM, value, 0)) %>%
                    filter(value > 0) %>%
                     mutate(rn = substr(.$rn, 1, 3)) %>%
                      group_by(rn) %>%
                       summarise(Inm = sum(value, na.rm = TRUE))                                     
              
filtro_cn <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value =  ifelse((.$rn != .$cn) & .$rn %in% ZM |.$cn %in% ZM, value, 0)) %>% 
                    filter(value > 0) %>%
                     mutate(cn = substr(.$cn, 1, 3)) %>%
                      group_by(cn) %>%
                       summarise(Emg = sum(value, na.rm = TRUE))  

filtro_estados <- filtro_rn %>%
                   full_join(., filtro_cn, by = c("rn" = "cn")) %>%
                    mutate(value = sum_row(.$Inm, .$Emg, na.rm = TRUE)) %>%
                     filter(value > 50000) %>%
                      pull(rn)

################################################################################


tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%                       
               mutate(rn = case_when(.$rn %in% ZM & .$rn %nin% filtro ~ .$rn,
                                     .$rn %in% ZM & .$rn %in% filtro ~ paste(substr(.$rn, 1, 3), "Municipios ZM"),
                                     .$rn %nin% ZM  &  substr(.$rn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]),
                                     .$rn %nin% ZM  &  substr(.$rn, 1, 3) %nin% filtro_estados ~ "Otros estados"),
                      cn = case_when(.$cn %in% ZM & .$cn %nin% filtro ~ .$cn,
                                     .$cn %in% ZM & .$cn %in% filtro ~ paste(substr(.$cn, 1, 3), "Municipios ZM"),
                                     .$cn %nin% ZM  &  substr(.$cn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]),
                                     .$cn %nin% ZM  &  substr(.$cn, 1, 3) %nin% filtro_estados ~ "Otros estados")) %>%
                filter(value > 0) 


p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/GSankey de MR5a de la ZMVM.pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_RES) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_RES) %>%
                     group_by(CVE_MUN_RES) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_RES") 

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020.RData"))
Indicadores de migración reciente
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 869 741 811 844 47 898 26 761 21 137 74 659 10.6 5.9 4.7 −53 522
001002 51 474 45 915 44 223 1 389 1 847 −458 3 236 5.7 7.6 −1.9 −3 694
001003 58 155 52 621 50 577 1 088 1 388 −300 2 476 3.9 5.0 −1.1 −2 776
001004 16 997 15 218 14 634 507 334 173 841 6.3 4.1 2.1 −668
001005 129 859 117 323 107 678 8 506 2 964 5 542 11 470 13.8 4.8 9.0 −5 928
001006 47 557 42 949 40 671 2 030 1 469 561 3 499 9.0 6.5 2.5 −2 938
001007 57 269 50 985 49 027 1 532 1 808 −276 3 340 5.7 6.7 −1.0 −3 616
001008 9 552 8 465 8 174 214 459 −245 673 4.8 10.2 −5.4 −918
001009 22 461 20 180 19 446 620 780 −160 1 400 5.8 7.3 −1.5 −1 560
001010 20 382 18 118 17 365 546 1 047 −501 1 593 5.7 10.9 −5.2 −2 094
001011 61 986 54 715 46 088 8 168 1 842 6 326 10 010 28.0 6.3 21.7 −3 684
002001 440 624 408 720 376 054 24 607 15 129 9 478 39 736 11.6 7.1 4.5 −30 258
002002 1 042 395 974 962 929 519 31 520 20 829 10 691 52 349 6.2 4.1 2.1 −41 658
002003 102 896 94 486 83 911 8 438 5 569 2 869 14 007 17.1 11.3 5.8 −11 138
002004 1 910 568 1 763 745 1 546 345 159 071 59 011 100 060 218 082 17.3 6.4 10.9 −118 022
002005 126 264 118 173 101 415 10 279 6 342 3 937 16 621 16.8 10.4 6.4 −12 684
002006 117 050 104 805 91 557 12 094 0 12 094 12 094 21.8 0.0 21.8 0
003001 72 358 67 109 64 658 2 192 3 939 −1 747 6 131 6.3 11.3 −5.0 −7 878
003002 62 884 57 738 54 515 2 759 5 421 −2 662 8 180 9.1 18.0 −8.8 −10 842
003003 290 063 270 823 249 997 17 969 11 442 6 527 29 411 12.8 8.2 4.7 −22 884
Fuente: Estimaciones del CONAPO.

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migración intramunicipal

Matrices

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, CVE_ZM, MC, CF, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2020 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intramunicipal.RDS"))

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 20)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel municipal, 2015 - 2020

Matriz de migración reciente por zonas metropolitanas
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 811844 0 0 0 1335 0 0 0 0 0 655 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 44223 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 50577 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 14634 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 3166 0 0 0 107678 0 0 0 0 0 201 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 40671 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 49027 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 8174 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 19446 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 17365 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2240 0 0 0 536 0 0 0 0 0 46088 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 376054 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 929519 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 83911 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1546345 2894 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1299 101415 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 91557 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64658 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 54515 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 249997 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 260221 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15609 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52125 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 257197 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 210329 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 67521 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28556 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 36662 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7728
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Matrices por zonas metropolitanas

MR <- NULL
for(i in 1:length(zm)){
tabla <- ZM_2020 %>%
          select(CVE_ZM, CVE_MUN) %>%
           filter(CVE_ZM %in% zm[i]) %>%
            pull(CVE_MUN)

MR[[paste0(zm[i])]] <- Migrantes %>%
                        as.data.frame() %>%
                         tibble::rownames_to_column(var = "CVE_MUN") %>%
                          mutate_if(is.numeric, as.numeric) %>%
                           select(CVE_MUN, all_of(tabla)) %>%
                            filter(CVE_MUN %in% tabla)
}

# Se guardan en un objeto de R 
saveRDS(MR, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2020.RDS"))

# Se genera un Excel con todas las matrices por ZM
wb <- createWorkbook()
for(i in 1:length(zm)){
addWorksheet(wb, paste0(zm[i]))
writeData(wb, i, MR[[paste0(zm[i])]] %>% as.data.frame())
saveWorkbook(wb, 
              file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2020.xlsx"), 
               overwrite = TRUE)
}

Matriz de migración reciente hace 5 años en la Zona Metropolitana de Cuernavaca, 2015 - 2020

Matriz de migración reciente a nivel intramunicipal
Zona Metropolitana de Cuernavaca
CVE_MUN 017007 017008 017009 017011 017018 017020 017028 017029 017034 017035
017007 320555 469 110 2908 1113 185 290 218 92 30
017008 3949 82835 58 2509 967 66 785 179 11 60
017009 972 29 19483 103 57 3 25 14 0 3
017011 4017 857 26 180659 540 348 120 448 0 54
017018 1865 425 0 877 102261 54 509 34 0 0
017020 494 55 12 536 124 46513 72 359 0 0
017028 918 551 18 334 1108 50 57135 72 0 0
017029 565 0 28 725 104 117 159 90266 0 0
017034 48 2 0 4 18 0 21 0 10065 2
017035 60 4 0 6 11 0 46 2 5 25030
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 3) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################# Filtro #######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
### Filtro <<<<  filter(value > 0 & rn != estado[x])
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
tabla1 <- lapply(1:length(ZM), function(x){
                                filtro  <- Inmigrantes[[x]] %>%
                                            full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                              filter(value < filtro_mig[x]) %>% 
                                               pull(rn)
                                 Migrantes %>%
                                  as.data.frame() %>%
                                   tibble::rownames_to_column(var = "rn") %>% 
                                    melt(., id.vars = "rn", variable.name = "cn") %>%
                                     mutate_if(is.factor, as.character) %>%
                                      filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                       mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                        mutate(rn = ifelse(.$rn %in% filtro, 
                                                           stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 100), 
                                                           substr(.$rn, 2, nchar(.$rn))),
                                               cn = ifelse(.$cn %in% filtro, 
                                                           stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 100), 
                                                           substr(.$cn, 2, nchar(.$cn)))) %>%
                                         filter(value > 0) %>%
                                          dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                           column_to_rownames(., var = "rn")
})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM), function(i){
#                                             tabla1[[i]] %>%
#                                              as.data.frame() %>%
#                                               adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#})

## Se guardan las matrices de Movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intramunicipal.RDS"))

#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (Intramunicipal).pdf"


## Gráficos a nivel intramunicipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family <- "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas ZM a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
) 
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/GSankey de MR5a desagregado por ZM_Absolutos (Intramunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 15000) %>% 
               pull(rn)

################################################################################
tabla1 <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
               filter(.$rn %in% ZM | .$cn %in% ZM) %>%
                mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
                 mutate(rn = ifelse(.$rn %in% filtro, 
                                    stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 30), 
                                    substr(.$rn, 2, nchar(.$rn))),
                        cn = ifelse(.$cn %in% filtro, 
                                    stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios (", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 30), 
                                    substr(.$cn, 2, nchar(.$cn)))) %>%
                  filter(value > 0) %>%
                   dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                    column_to_rownames(., var = "rn")
groupColors <- paste0(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a de ZMVM (Intramunicipal).pdf"), 
          width = 7, height = 7, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(1.5, 4))

# Paleta de colores
groupColors <- setNames(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 0.2, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(7),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(5),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

dev.off()
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 15000) %>% 
               pull(rn)
################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% filtro ~ stringr::str_wrap(paste(substr(as.character(.$rn), 2, 3), "Otros municipios (", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 30), 
                                     .$rn %nin% filtro ~ substr(.$rn, 2, nchar(.$rn))),
                       cn = case_when(.$cn %in% filtro ~ stringr::str_wrap(paste(substr(as.character(.$cn), 2, 3), "Otros municipios (", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 30),  
                                      .$cn %nin% filtro ~substr(.$cn, 2, nchar(.$cn)))) %>%
                 filter(value > 0) 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a de ZMVM a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a de ZMVM_grupos (Intramunicipal).pdf"), 
          width = 10, height = 10, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)
 
circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(0, 4))

# Paleta de colores
groupColors <- setNames(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 1, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(9),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(7),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

highlight.sector(grupo1, 
                 track.index = 1, 
                 col = groupColors[1], 
                 text = "Ciudad de México", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), niceFacing = TRUE)

highlight.sector(grupo2, 
                 track.index = 1, 
                 col = groupColors[15], 
                 text = "México", 
                 cex = 1.5, 
                 text.col = "white",
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo3, 
                 track.index = 1, 
                 col = groupColors[20], 
                 text = "Hidalgo", 
                 cex = 1, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)
dev.off()

Etiquetas

etiquetas  <- lapply(1, function(x){
                        orden <- str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)
                        p <-  tabla1 %>% 
                               as.data.frame() %>%
                                tibble::rownames_to_column(var = "rn") %>%
                                 melt(., id.vars = "rn", variable.name = "cn") %>%
                                  as.data.frame() %>% 
                                   mutate(rn = str_wrap(.$rn, 100),
                                          cn = str_wrap(.$cn, 100)) %>%
                                    ggplot() + 
                                     geom_bar(aes(x = value, fill = as.character(rn, orden)))  + 
                                      geom_bar(aes(x = value, fill = as.character(cn, orden)))  + 
                                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                             text = element_text(family = "Montserrat Medium"),
                                             axis.text = element_blank(),
                                             axis.title = element_blank(),
                                             strip.text = element_text(size = 9, face = "bold", family = "Montserrat Medium"),  
                                             legend.key.size = unit(0.4, "cm"), 
                                             legend.spacing.y = unit(0.4, "cm"),
                                             legend.text = element_text(size = 7, family = "Montserrat Medium"),
                                             legend.title = element_text(size = 8 , family = "Montserrat Medium")) + 
                                       scale_fill_manual(values = colorRampPalette(paleta)(max(ncol(tabla1), nrow(tabla1)))) + 
                                         guides(fill = guide_legend(ncol = 1)) + 
                                        guides(fill = guide_legend(ncol = 1)) + 
                                         labs(fill = "ZM del Valle de México",
                                          color = "ZM del Valle de México")
                         leg <- get_legend(p)
                         as_ggplot(leg)
 })

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas ZMVM a nivel intramunicipal.pdf"), 
          width = 7, height = 8, 
          fallback_resolution = 400,
          family = "montserrat", onefile = TRUE)
for(i in 1){
  print(etiquetas[i])
}
dev.off()
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 20), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 20) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(),"/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/GSankey de MR5a de la ZMVM (Intramunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_RES) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_RES) %>%
                     group_by(CVE_MUN_RES) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_RES") 

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intramunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intramunicipal).RData"))
Indicadores de migración reciente
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 869 741 811 844 1 990 5 406 −3 416 7 396 0.44 1.19 −0.8 −10 812
001002 51 474 45 915 44 223 0 0 0 0 0.00 0.00 0.0 0
001003 58 155 52 621 50 577 0 0 0 0 0.00 0.00 0.0 0
001004 16 997 15 218 14 634 0 0 0 0 0.00 0.00 0.0 0
001005 129 859 117 323 107 678 3 367 1 871 1 496 5 238 5.45 3.03 2.4 −3 742
001006 47 557 42 949 40 671 0 0 0 0 0.00 0.00 0.0 0
001007 57 269 50 985 49 027 0 0 0 0 0.00 0.00 0.0 0
001008 9 552 8 465 8 174 0 0 0 0 0.00 0.00 0.0 0
001009 22 461 20 180 19 446 0 0 0 0 0.00 0.00 0.0 0
001010 20 382 18 118 17 365 0 0 0 0 0.00 0.00 0.0 0
001011 61 986 54 715 46 088 2 776 856 1 920 3 632 9.51 2.93 6.6 −1 712
002001 440 624 408 720 376 054 0 0 0 0 0.00 0.00 0.0 0
002002 1 042 395 974 962 929 519 0 0 0 0 0.00 0.00 0.0 0
002003 102 896 94 486 83 911 0 0 0 0 0.00 0.00 0.0 0
002004 1 910 568 1 763 745 1 546 345 2 894 1 299 1 595 4 193 0.32 0.14 0.2 −2 598
002005 126 264 118 173 101 415 1 299 2 894 −1 595 4 193 2.13 4.74 −2.6 −5 788
002006 117 050 104 805 91 557 0 0 0 0 0.00 0.00 0.0 0
003001 72 358 67 109 64 658 0 0 0 0 0.00 0.00 0.0 0
003002 62 884 57 738 54 515 0 0 0 0 0.00 0.00 0.0 0
003003 290 063 270 823 249 997 0 0 0 0 0.00 0.00 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermunicipal

Matrices

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, CVE_ZM, MC, CF, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2020 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intermunicipal.RDS"))

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 20)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel intermunicipal, 2015 - 2020

Matriz de migración reciente por zonas metropolitanas
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 835 491 0 0 440 550 177 177 571 0 183 426 0 120 59 0 0 177 0 0 0 0 0 0 0 0 0 0
001002 330 0 10 5 28 15 33 0 72 56 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 139 0 0 0 20 0 21 0 0 0 0 4 6 6 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 75 3 0 0 16 3 80 0 18 0 2 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0
001005 0 199 19 34 0 98 46 30 89 46 0 0 9 0 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 199 5 36 5 177 0 234 2 50 0 358 0 4 0 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 238 13 25 135 33 93 0 26 82 0 61 0 0 0 28 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 41 2 2 0 20 28 12 0 35 0 8 4 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 75 31 0 15 0 73 153 0 0 0 41 0 8 3 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 219 18 0 0 5 0 2 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 203 160 2 0 523 21 92 67 5 0 0 0 0 0 156 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 14 0 0 0 0 0 0 0 0 0 1737 214 2213 115 449 1032 701 245 56 0 0 0 0 0 0 0 0
002002 174 67 0 0 0 0 0 0 0 0 0 1139 0 755 1677 347 0 48 79 150 0 0 0 0 0 0 0 0 0
002003 70 0 0 0 0 0 0 0 0 0 0 52 865 0 1214 49 25 0 0 97 0 0 0 0 0 0 0 0 0
002004 165 0 0 0 0 0 0 0 0 0 0 1433 2600 1716 0 0 0 648 965 913 0 0 165 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 176 307 149 0 0 0 0 65 25 0 0 24 37 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 82 0 267 0 0 460 70 150 66 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 39 59 0 28 0 0 234 496 297 137 0 8 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 786 225 11 119 18 135 0 173 43 22 0 0 0 0 0 0 0 0
003003 20 0 0 0 0 0 0 0 0 0 0 494 225 0 643 0 1741 1082 0 2700 348 0 0 0 0 0 0 0 0
003008 119 0 0 0 0 0 0 0 0 0 0 272 174 26 426 221 237 287 981 0 185 0 76 0 28 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 26 12 0 63 0 98 26 169 12 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 284 96 137 122 83 0 0
004002 17 0 0 0 0 0 0 0 0 0 0 40 0 0 51 0 0 49 0 0 0 182 0 1080 736 120 494 54 114
004003 32 0 0 0 0 0 0 0 0 0 0 0 0 0 11 0 0 0 0 0 0 81 525 0 452 0 0 33 0
004004 0 0 0 0 0 0 0 0 0 0 0 36 0 0 7 0 0 0 0 0 0 0 217 469 0 0 0 0 7
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 20 139 9 56 0 26 0 53
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92 0 7 5 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 33 2 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 5 139 12 2 22 5 2 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    # filtro de municipios de la ZM
                                      filtro  <- Inmigrantes[[x]] %>%
                                                  full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                    mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                      filter(value > filtro_mig[x]) %>%   ## Cambia el filtro de los municipios de la Zonas Metropolitanas
                                                       pull(rn)
                                      
                                     
                                    # filtro de estados
                                     filtro_est <- Inmigrantes[[x]] %>%
                                                    full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                     filter(rn %nin% ZM[[x]]) %>%
                                                      mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                       mutate(rn = substr(.$rn, 1, 3)) %>%
                                                        group_by(rn) %>%
                                                         summarise(value = sum(value)) %>%
                                                          filter(value >= filtro_out[x]) %>% 
                                                           pull(rn)
                                     
                                     Migrantes %>%
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "rn") %>% 
                                        melt(., id.vars = "rn", variable.name = "cn") %>%
                                         mutate_if(is.factor, as.character) %>%
                                          filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                           mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                            mutate(rn = case_when(.$rn %in% ZM[[x]] & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                                                  .$rn %in% ZM[[x]] & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZM"), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                                                  .$rn %nin% ZM[[x]] & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                                                   cn = case_when(.$cn %in% ZM[[x]] & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                                                  .$cn %in% ZM[[x]] & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZM"), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                                                  .$cn %nin% ZM[[x]] & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                                            filter(value > 0) %>%
                                             dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                              column_to_rownames(., var = "rn") 
  }
)

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/100) %>%
#                                                    pull(Total)
#                              }
#})

## Se guardan las matrices de migración reciente para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-",   
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Tabla MR5a a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Tabla MR5a a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Tabla MR5a a nivel intermunicipal.RDS"))

#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (Intermunicipal).pdf"
 
## Gráficos a nivel intermunicipal 
chord_diagram_graph(file = file, 
                    width = 15,
                    height = 10,
                    family <- "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas ZM a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Gráfico Sankey

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN), by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 25)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 3) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

################################################################################

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                    ZM <- ZM_2020 %>%
                                           select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                            filter(CVE_ZM %in% ZM_CF[x])  %>%
                                             mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                              pull(NOM_MUN)
                                    
                                    # filtro de municipios metropolitanos
                                     filtro <- filtro %>%
                                      filter(rn %in% ZM) %>%
                                       filter(value < 1000) %>%
                                        pull(rn)
                                     
                                    # filtro de estados
                                     filtro_rn  <- filtro_est %>%
                                                    mutate(value = ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>%
                                                     mutate(rn = substr(.$rn, 1, 3)) %>%
                                                      group_by(rn) %>%
                                                       summarise(Inm = sum(value, na.rm = TRUE))
              
                                     filtro_cn  <- filtro_est %>%
                                                    mutate(value =  ifelse(.$rn %nin% filtro |.$cn %nin% filtro, value, 0)) %>% 
                                                     mutate(cn = substr(.$cn, 1, 3)) %>%
                                                      group_by(cn) %>%
                                                       summarise(Emg = sum(value, na.rm = TRUE))
              
                                     filtro_estados <- filtro_rn %>%
                                                        full_join(., filtro_cn, by = c("rn" = "cn")) %>%
                                                         mutate(value = sum_row(.$Inm, .$Emg, na.rm = TRUE)) %>%
                                                          filter(value > 50000) %>%
                                                           pull(rn)
                                     
                                     tabla %>%
                                      mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), .$value, 0)) %>%
                                       mutate(rn = case_when(.$rn %in% ZM & .$rn %nin% filtro ~ .$rn,
                                                             .$rn %in% ZM & .$rn %in% filtro ~ paste(substr(.$rn, 1, 3), "Municipios ZM"),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]),
                                                             .$rn %nin% ZM  &  substr(.$rn, 1, 3) %nin% filtro_estados ~ "Otros estados"),
                                              cn = case_when(.$cn %in% ZM & .$cn %nin% filtro ~ .$cn,
                                                             .$cn %in% ZM & .$cn %in% filtro ~ paste(substr(.$cn, 1, 3), "Municipios ZM"),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %in% filtro_estados ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]),
                                                             .$cn %nin% ZM  &  substr(.$cn, 1, 3) %nin% filtro_estados ~ "Otros estados")) %>%
                                        filter(value > 0)
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(),"/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/GSankey de MR5a desagregado por ZM_Absolutos (Intermunicipal).pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 11000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 13000) %>%
                      pull(rn)

################################################################################
tabla1 <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 50),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 50),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 50),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 50),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0) %>%
                  dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                   column_to_rownames(., var = "rn") 
# Grupo de colores
groupColors <- paste0(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a de ZMVM (Intermunicipal).pdf"), 
          width = 7, height = 7, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)

circos.clear()
circos.par(start.degree = 90, 
           clock.wise = TRUE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(1.5, 4))

# Paleta de colores
groupColors <- setNames(rev(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1)))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 0.2, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(7),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(5),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

dev.off()
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 11000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 15000) %>%
                      pull(rn)

################################################################################
tabla <- Migrantes %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
              filter(.$rn %in% ZM | .$cn %in% ZM) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM| .$cn %in% ZM), value, 0)) %>% 
                mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ substr(.$rn, 2, nchar(.$rn)),
                                      .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$rn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 100),
                                      .$rn %nin% ZM & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                                                 
                       cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ substr(.$cn, 2, nchar(.$cn)),
                                      .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(substr(estados[as.numeric(substr(.$cn, 1, 3))], 2, 3), "ZMVM"), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 100),
                                      .$cn %nin% ZM & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                 filter(value > 0)  

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a de ZMVM a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a de ZMVM_grupos (Intermunicipal).pdf"), 
          width = 10, height = 10, 
          family = "Montserrat Medium",
          fallback_resolution = 400,
          onefile = TRUE)
 
circos.clear()
circos.par(start.degree = 90, 
           clock.wise = FALSE,
           gap.degree = 3, 
           track.margin = c(-0.2, 0.2), 
           points.overflow.warning = FALSE)

par(mar = rep(0, 4))

# Paleta de colores
groupColors <- setNames(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))),
                                               nm = unique(c(colnames(tabla1), rownames(tabla1))))

chordDiagram(x = tabla1 %>% as.matrix(), 
             grid.col = groupColors,
             order = union(rownames(tabla1), colnames(tabla1)),
             keep.diagonal = FALSE,
             symmetric = FALSE,
             scale = FALSE, 
             transparency = 0.25,
             directional = 1,
             direction.type = c("arrows", "diffHeight"), 
             diffHeight  = -0.04,
             annotationTrack = "grid", 
             annotationTrackHeight = mm_h(c(3)), # ancho borde
             preAllocateTracks = 1, 
             big.gap = 40,
             link.arr.type = "big.arrow", 
             link.lwd = 0.5,
             link.visible = TRUE,
             link.largest.ontop = FALSE)
# Add text and axis
circos.trackPlotRegion(track.index = 1,
                       track.height = 0.05,
                       bg.border = NA, 
                       panel.fun = function(x, y) {
                                                   xlim = get.cell.meta.data("xlim")
                                                   ylim = get.cell.meta.data("ylim")
                                                   sector.name = get.cell.meta.data("sector.index")
                                                  # Add names to the sector. 
                                                   circos.text(x = mean(xlim), 
                                                               y = ylim[1] + 1, #Ajusta a las etiquetas del origen 
                                                               labels = sector.name, 
                                                               facing = "clockwise",
                                                               niceFacing = TRUE, 
                                                               adj = c(-0.01, 0.5), #Ajuste de las etiquetas (x, y)
                                                               cex = fontsize(9),
                                                               col = "#000C7D",
                                                               font = 1)
                                                  # Add graduation on axis
                                                   circos.axis(h = "top",
                                                               labels = c(0, 10, 20, 50, 100, 200, 300, 400, 500, 1000, seq(1000, 20000, by = 100000)),
                                                               major.tick.length = 0.2,
                                                               minor.ticks = 2, 
                                                               labels.cex = fontsize(7),
                                                               sector.index = sector.name,
                                                               track.index = 2,
                                                               labels.niceFacing = TRUE,
                                                               labels.pos.adjust = c(0, 0.8))
                                                }
  )

highlight.sector(grupo1, 
                 track.index = 1, 
                 col = groupColors[1], 
                 text = "Ciudad de México", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), niceFacing = TRUE)

highlight.sector(grupo2, 
                 track.index = 1, 
                 col = groupColors[15], 
                 text = "México", 
                 cex = 1.5, 
                 text.col = "white",
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo3, 
                 track.index = 1, 
                 col = groupColors[20], 
                 text = "Hidalgo", 
                 cex = 1, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

highlight.sector(grupo4, 
                 track.index = 1, 
                 col = groupColors[30], 
                 text = "Otro municipios", 
                 cex = 1.5, 
                 text.col = "white", 
                 padding = c(-0.5, 0, -0.2, 0), 
                 niceFacing = TRUE)

dev.off()

Etiquetas

etiquetas  <- lapply(1, function(x){
                        orden <- str_sort(unique(c(colnames(tabla1), rownames(tabla1))), numeric = TRUE)
                        p <-  tabla1 %>% 
                               as.data.frame() %>%
                                tibble::rownames_to_column(var = "rn") %>%
                                 melt(., id.vars = "rn", variable.name = "cn") %>%
                                  as.data.frame() %>% 
                                   mutate(rn = str_wrap(.$rn, 100),
                                          cn = str_wrap(.$cn, 100)) %>%
                                    ggplot() + 
                                     geom_bar(aes(x = value, fill = as.character(rn, orden)))  + 
                                      geom_bar(aes(x = value, fill = as.character(cn, orden)))  +  
                                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                             text = element_text(family = "Montserrat Medium"),
                                             axis.text = element_blank(),
                                             axis.title = element_blank(),
                                             strip.text = element_text(size = 9, face = "bold", family = "Montserrat Medium"),  
                                             legend.key.size = unit(0.4, "cm"), 
                                             legend.spacing.y = unit(0.4, "cm"),
                                             legend.text = element_text(size = 7, family = "Montserrat Medium"),
                                             legend.title = element_text(size = 8 , family = "Montserrat Medium")) + 
                                       scale_fill_manual(values = colorRampPalette(paleta)(max(ncol(tabla1), nrow(tabla1)))) + 
                                         guides(fill = guide_legend(ncol = 1)) + 
                                        guides(fill = guide_legend(ncol = 1)) + 
                                         labs(fill = "ZM del Valle de México",
                                          color = "ZM del Valle de México")
                         leg <- get_legend(p)
                         as_ggplot(leg)
 })

cairo_pdf(paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas ZMVM a nivel intermunicipal.pdf"),
          width = 7, height = 9, 
          fallback_resolution = 400,
          family = "montserrat", onefile = TRUE)
for(i in 1){
  print(etiquetas[i])
}
dev.off()
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value > 30000) %>% 
                pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ .$rn,
                                     .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 20)),
                       
                      cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ .$cn,
                                     .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 20))) %>%
                filter(value > 0) 


p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/GSankey de MR5a de la ZMVM (Intermunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <= 130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_RES) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_RES) %>%
                     group_by(CVE_MUN_RES) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_RES") 

tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intermunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intermunicipal).RData"))
Indicadores de migración reciente
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 869 741 0 45 908 21 355 24 553 67 263 10.1 4.7 5.4 −42 710
001002 51 474 45 915 0 1 389 1 847 −458 3 236 5.7 7.6 −1.9 −3 694
001003 58 155 52 621 0 1 088 1 388 −300 2 476 3.9 5.0 −1.1 −2 776
001004 16 997 15 218 0 507 334 173 841 6.3 4.1 2.1 −668
001005 129 859 117 323 0 5 139 1 093 4 046 6 232 8.3 1.8 6.5 −2 186
001006 47 557 42 949 0 2 030 1 469 561 3 499 9.0 6.5 2.5 −2 938
001007 57 269 50 985 0 1 532 1 808 −276 3 340 5.7 6.7 −1.0 −3 616
001008 9 552 8 465 0 214 459 −245 673 4.8 10.2 −5.4 −918
001009 22 461 20 180 0 620 780 −160 1 400 5.8 7.3 −1.5 −1 560
001010 20 382 18 118 0 546 1 047 −501 1 593 5.7 10.9 −5.2 −2 094
001011 61 986 54 715 0 5 392 986 4 406 6 378 18.5 3.4 15.1 −1 972
002001 440 624 408 720 0 24 607 15 129 9 478 39 736 11.6 7.1 4.5 −30 258
002002 1 042 395 974 962 0 31 520 20 829 10 691 52 349 6.2 4.1 2.1 −41 658
002003 102 896 94 486 0 8 438 5 569 2 869 14 007 17.1 11.3 5.8 −11 138
002004 1 910 568 1 763 745 0 156 177 57 712 98 465 213 889 17.0 6.3 10.7 −115 424
002005 126 264 118 173 0 8 980 3 448 5 532 12 428 14.7 5.6 9.1 −6 896
002006 117 050 104 805 0 12 094 0 0 0 21.8 0 0 0
003001 72 358 67 109 0 2 192 3 939 −1 747 6 131 6.3 11.3 −5.0 −7 878
003002 62 884 57 738 0 2 759 5 421 −2 662 8 180 9.1 18.0 −8.8 −10 842
003003 290 063 270 823 0 17 969 11 442 6 527 29 411 12.8 8.2 4.7 −22 884
Fuente: Estimaciones del CONAPO.

Migración metropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, CVE_ZM, MC, CF, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2020 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_metropolitana.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_metropolitana.RDS"))

Migrantes <- svytable(~CVE_ZM_RES + CVE_ZM, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ZM, CVE_ZM_RES, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_ZM" = "row_labels") %>% 
                  arrange(CVE_ZM) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_ZM = substr(.$CVE_ZM, 8, 12)) %>% 
              pull(CVE_ZM)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_ZM" = ".") %>%
                mutate(`CVE_ZM` = substr(.$CVE_ZM, 12, 16)) %>%
                 pull(CVE_ZM)

# Se elimina la variable CVE_ZM
Migrantes <- Migrantes %>%
              select(-CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Metropolitano")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_ZM"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2020.xlsx"), overwrite = TRUE)

Matriz de migración reciente hace 5 años a nivel municipal, 2015 - 2020

Matriz de migración reciente por zonas metropolitanas
Nivel municipal
CVE_ZM 01.01 02.01 02.02 02.03 03.01 03.02 04.01 05.01 05.02 05.03 05.04 05.05 06.01 06.02 07.01 07.02 08.01 08.02 08.03 08.04 09.01 10.01 11.01 11.02 11.03 11.04 11.06 11.07 12.01
01.01 973743 183 435 365 177 0 0 322 0 2 365 0 195 9 177 59 542 60 0 1227 7.5e+03 192 533 289 1511 72 204 0 344
02.01 0 376054 1737 2328 701 245 0 125 0 0 0 0 57 64 328 144 335 49 0 7 1.4e+03 229 0 314 7 0 27 140 492
02.02 174 1139 929519 2024 79 150 0 79 16 0 280 0 0 680 0 246 428 144 276 229 1.0e+03 0 203 140 15 0 0 67 24
02.03 165 1609 2907 1651953 1030 938 189 838 0 79 241 0 1554 357 6554 2150 804 0 0 1124 8.8e+03 1254 181 243 285 102 938 89 11641
03.01 20 494 225 643 249997 2700 0 10 21 0 183 0 20 0 140 80 10 0 0 0 1.5e+03 204 22 101 0 0 20 0 201
03.02 119 272 174 647 981 260221 76 140 0 23 30 0 112 0 968 146 273 0 0 53 4.4e+03 216 25 226 27 0 0 0 6126
04.01 17 40 0 51 0 0 257197 0 0 22 0 0 34 0 43 37 0 0 0 18 7.8e+02 0 0 0 0 0 0 0 53
05.01 46 113 88 443 0 121 0 1212336 303 271 652 9 16 0 0 0 1701 145 103 3086 1.7e+03 2631 15 67 8 20 165 0 18
05.02 32 0 0 20 0 0 11 250 332970 363 650 176 10 0 0 11 56 0 14 29 1.6e+02 22 20 21 36 0 0 0 0
05.03 0 0 0 0 0 0 16 313 916 177947 246 601 24 0 0 17 5 0 56 0 2.2e+02 114 15 66 72 0 108 0 27
05.04 157 56 16 131 64 0 0 2821 3490 788 876913 643 0 0 587 902 146 0 0 552 1.6e+03 232 129 98 0 227 301 0 16
05.05 0 0 0 0 0 0 0 13 181 172 112 95954 0 0 12 13 0 0 0 0 6.1e+01 0 0 0 0 0 0 0 0
06.01 73 89 80 358 0 96 0 24 0 10 63 0 276969 3442 0 53 75 0 26 292 1.0e+03 26 51 51 48 0 79 0 48
06.02 10 59 22 130 0 63 12 0 0 0 0 0 802 122359 329 0 7 0 0 13 1.8e+02 3 103 37 47 12 5 0 155
07.01 2 216 0 752 36 186 33 0 0 3 0 0 18 0 338250 651 16 16 0 178 1.2e+03 0 4 17 18 0 6 0 95
07.02 5 0 5 174 0 58 30 42 10 0 24 0 6 0 537 750839 5 0 0 47 1.7e+03 0 41 88 54 0 194 0 144
08.01 136 69 144 298 156 69 0 1393 20 69 138 0 148 0 0 0 867666 1969 1635 2334 9.5e+02 103 10 4 349 0 0 0 69
08.02 19 46 26 75 60 5 0 138 34 45 0 0 10 0 0 0 849 185585 269 697 2.3e+02 111 0 0 0 0 0 0 10
08.03 0 0 0 2 18 17 0 108 0 0 54 0 0 0 0 0 1058 3 104039 348 4.0e+00 87 0 18 0 0 0 0 0
08.04 568 0 0 1110 0 0 219 4896 119 0 216 0 0 0 766 327 4927 445 2408 1285749 9.1e+02 7471 0 702 0 0 228 0 226
09.01 3375 1027 1001 3807 1337 796 1054 1409 49 72 735 13 855 161 1234 1634 2080 141 37 2045 1.9e+07 1260 1083 2238 3130 31 1052 226 6732
10.01 529 0 43 1001 40 83 0 916 0 41 74 0 48 0 0 50 538 0 121 1340 1.1e+03 599224 295 82 167 0 696 0 182
11.01 248 0 0 99 0 0 0 0 0 0 82 0 12 112 5 29 10 56 0 0 8.8e+02 0 615072 79 223 48 236 46 12
11.02 165 32 0 24 0 0 0 42 0 12 73 0 25 0 35 0 8 0 0 16 6.1e+02 153 323 168732 1230 120 633 205 23
11.03 604 0 10 677 0 69 0 42 594 268 0 0 93 0 10 203 235 0 134 140 5.5e+03 308 919 892 1690807 276 2385 1143 723
11.04 4 0 0 4 0 0 0 0 8 0 0 0 0 9 0 0 16 0 0 0 1.5e+02 4 24 8 15 126879 52 0 0
11.06 141 0 27 527 27 0 0 26 0 0 160 0 68 0 0 27 27 0 0 49 2.1e+03 55 562 406 702 0 517521 125 0
11.07 126 0 15 0 0 5 0 51 12 5 25 0 0 0 11 0 106 27 0 45 9.9e+02 22 112 180 1030 11 257 233107 32
12.01 0 375 0 583 0 539 0 0 0 51 48 0 60 0 0 257 48 0 0 0 3.4e+03 0 0 150 0 0 48 0 695479
12.02 0 0 32 71 0 10 0 0 0 0 29 0 32 0 0 0 0 0 0 5 8.8e+02 29 16 29 0 0 0 0 1547
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)


################################################################################
tabla1 <- lapply(1, function(x){
                         Migrantes %>%
                          as.data.frame() %>%
                           tibble::rownames_to_column(var = "rn") %>% 
                            melt(., id.vars = "rn", variable.name = "cn") %>%
                             mutate_if(is.factor, as.character) %>%
                              mutate(value = ifelse((.$rn != .$cn), value, 0)) %>% 
                               filter(value > 0) %>%
                                dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                 column_to_rownames(., var = "rn") 
}
)
#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = 1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (metropolitano).pdf"

## Gráficos a nivel metropolitano 
chord_diagram_graph(file = file, 
                    width = 10,
                    height = 10,
                    family = "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = 1, #Longuitud 1
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))
Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de MR5a a nivel metropolitano 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
ZM <- ZM_2020 %>% 
       select(CVE_ZM, NOM_ZM) %>% 
        distinct(CVE_ZM, NOM_ZM) %>%
         mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
          pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM,
 #               filtro_zm = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel metropolitano.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Filtro a nivel metropolitano.xlsx"), colNames = TRUE) %>%
               pull(filtro_zm)

################################################################################
tabla1 <- lapply(1:length(ZM), function(x){
                                # filtro de estados
                                  filtro_zm <- Inmigrantes[[x]] %>%
                                                full_join(., Emigrantes[[x]], by = c("rn" = "cn")) %>%
                                                 filter(rn %nin% ZM[[x]]) %>%
                                                  mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                                   mutate(rn = substr(.$rn, 1, 5)) %>%
                                                    group_by(rn) %>%
                                                     summarise(value = sum(value)) %>%
                                                      filter(value >= filtro_mig[x]) %>% 
                                                       pull(rn)
                                Migrantes %>%
                                 as.data.frame() %>%
                                  tibble::rownames_to_column(var = "rn") %>% 
                                   melt(., id.vars = "rn", variable.name = "cn") %>%
                                    mutate_if(is.factor, as.character) %>%
                                     filter(.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]) %>%
                                       mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM[[x]] | .$cn %in% ZM[[x]]), value, 0)) %>% 
                                         mutate(rn = case_when(.$rn %in% ZM[[x]] ~ .$rn,
                                                               .$rn %nin% ZM[[x]] & substr(.$rn, 1, 5) %in% filtro_zm ~ .$rn,
                                                               .$rn %nin% ZM[[x]] & substr(.$rn, 1, 5) %nin% filtro_zm ~ "Otras zonas metropolitanas"),
                                                 
                                               cn = case_when(.$cn %in% ZM[[x]] ~ .$cn,
                                                               .$cn %nin% ZM[[x]] & substr(.$cn, 1, 5) %in% filtro_zm ~ .$cn,
                                                               .$cn %nin% ZM[[x]] & substr(.$cn, 1, 5) %nin% filtro_zm ~ "Otras zonas metropolitanas")) %>%
                                         filter(value > 0) %>%
                                          dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                           column_to_rownames(., var = "rn") 
  }
)
## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
     addWorksheet(wb, zm[i])
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel metropolitano_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel metropolitano.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel metropolitano.RDS"))

totales <- lapply(1:length(ZM), function(x){
                #Se agrupan los totales
                 full_join(
                           tabla1[[x]] %>%
                            as.data.frame() %>%
                             adorn_totals(c("row", "col"), 
                                          fill = "-", 
                                          na.rm = TRUE, 
                                           ,,,,contains(str_sort(unique(c(colnames(tabla1[[x]]), rownames(tabla1[[x]]))), numeric = TRUE))) %>%
                              slice(nrow(.)) %>% 
                               t() %>%
                                as.data.frame()%>%
                                 rownames_to_column(var = "name")  %>% 
                                  rename("Total_Filas" = "1"),
                           tabla1[[x]] %>%
                            as.data.frame() %>%
                             adorn_totals(c("row", "col"), 
                                          fill = "-", 
                                          na.rm = TRUE, 
                                           ,,,,contains(str_sort(unique(c(colnames(tabla1[[x]]), rownames(tabla1[[x]]))), numeric = TRUE))) %>%
                              rownames_to_column(var = "name") %>%
                               select(name, Total) %>%
                                mutate(name = str_replace(.$name, "1$", "Total")), 
                           by = c("name")
                           ) %>%
                           rename("CVE_MUN" = "name",
                                  "Emigrantes" = "Total_Filas",
                                  "Inmigrantes" = "Total") %>%
                            select(Inmigrantes, CVE_MUN, Emigrantes)
  }
)
porcentajes <- lapply(1:length(ZM), function(x){
                           #Se agrupan los porcentajes
                           full_join(
                                     tabla1[[x]] %>%
                                      as.data.frame() %>%
                                       adorn_totals(c("col", "row"), 
                                                    fill = "0", 
                                                    na.rm = TRUE, 
                                                    name = "Total",
                                                    ,,,,contains(str_sort(unique(c(colnames(tabla1[[x]]), rownames(tabla1[[x]]))), numeric = TRUE))) %>%
                                        adorn_percentages("col",
                                                          na.rm = TRUE) %>% 
                                         rownames_to_column(var = "name") %>%
                                          select(name, Total) %>%
                                           mutate(name = str_replace(.$name, "1$", "Total")),
                                     tabla1[[x]] %>%
                                      as.data.frame() %>%
                                       adorn_totals(c("row"), 
                                                    fill = "0", 
                                                    na.rm = TRUE, 
                                                    name = "Total", 
                                                    ,,,,contains(str_sort(unique(c(colnames(tabla1[[x]]), rownames(tabla1[[x]]))), numeric = TRUE))) %>%
                                        adorn_percentages("row", 
                                                          na.rm = TRUE, 
                                                         ,,,,contains(str_sort(unique(c(colnames(tabla1[[x]]), rownames(tabla1[[x]]))), numeric = TRUE))) %>%
                                         slice(nrow(.)) %>% 
                                          t() %>%
                                           as.data.frame()%>%
                                            rownames_to_column(var = "name")  %>% 
                                             rename("Total_Filas" = "1"), 
                                     by = c("name")
                                          ) %>%
                                      rename("CVE_MUN" = "name",
                                             "Emigrantes%" = "Total_Filas",
                                             "Inmigrantes%" = "Total") %>%
                                      select(`Inmigrantes%`, CVE_MUN, `Emigrantes%`)
                                   
  }
)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, totales[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel metropolitano_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz MR5a a nivel metropolitano.RDS"))

#paleta <- colorRampPalette(pals::kovesi.linear_bmy_10_95_c78(100))(50)
paleta <- c("#000C7D", "#00108D", "#02149C", "#1614A4", "#3012A6", "#5A0D9D", "#7A0895", "#910390", "#A7008A", "#BB0085", "#CE0080", "#DF047A", "#EE1774", "#FA2C6C", "#FD4364", "#FE595B", "#FF6F51", "#FF8445","#FF9636", "#FFA72B", "#FFB622")

tabla2 <- color_chord_diagram(tabla1, ZM_CF = ZM_CF, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/ChordDiagram de MR5a desagregado por ZM (metropolitano)_individual.pdf"

## Gráficos a nivel metropolitano 
chord_diagram_graph(file = file, 
                    width = 8,
                    height = 8,
                    family <- "Montserrat Medium",
                    paleta = paleta,
                    ZM_CF = ZM_CF,
                    tabla1,
                    tabla2,
                    color_labels = "#000C7D",
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Etiquetas ZM a nivel metropolitano.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     ZM_CF , 
                     tabla1, 
                     NOM_ZM_CF)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <= 130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel municipal.RData"))

ZM <- lapply(1:length(zm), function(x){
                 ZM_2020 %>% 
                  select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                   filter(CVE_ZM %in% zm[x])  %>% 
                    pull(CVE_MUN)
})


Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
}
)

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)


tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Metropolitano) 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Metropolitano) 2020.RData"))
Indicadores de migración reciente
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 1 137 351 1 041 779 965 610 64 572 31 567 33 005 96 139 11.9 5.8 6.1 −63 134
02.01 440 624 408 720 376 054 24 607 15 129 9 478 39 736 11.6 7.1 4.5 −30 258
02.02 1 042 395 974 962 929 519 31 520 20 829 10 691 52 349 6.2 4.1 2.1 −41 658
02.03 2 036 832 1 881 918 1 647 760 169 350 65 353 103 997 234 703 17.3 6.7 10.6 −130 706
03.01 290 063 270 823 249 997 17 969 11 442 6 527 29 411 12.8 8.2 4.7 −22 884
03.02 350 193 316 916 260 221 45 338 18 730 26 608 64 068 27.2 11.2 16.0 −37 460
04.01 293 199 271 217 257 197 12 224 17 211 −4 987 29 435 8.7 12.2 −3.5 −34 422
05.01 1 369 966 1 249 820 1 199 403 40 889 44 124 −3 235 85 013 6.2 6.7 −0.5 −88 248
05.02 374 001 339 271 331 883 6 115 12 062 −5 947 18 177 3.4 6.8 −3.3 −24 124
05.03 207 994 189 033 177 624 8 200 6 131 2 069 14 331 8.3 6.2 2.1 −12 262
05.04 1 028 156 936 122 868 898 50 752 29 320 21 432 80 072 10.3 6.0 4.4 −58 640
05.05 106 988 97 708 95 720 1 519 2 696 −1 177 4 215 3.0 5.3 −2.3 −5 392
06.01 326 478 304 710 269 821 29 970 23 497 6 473 53 467 19.0 14.9 4.1 −46 994
06.02 143 572 131 524 121 925 8 510 8 955 −445 17 465 12.4 13.0 −0.6 −17 910
07.01 397 226 359 067 337 555 11 546 25 697 −14 151 37 243 6.1 13.6 −7.5 −51 394
07.02 846 364 773 479 741 298 29 804 51 843 −22 039 81 647 7.4 12.8 −5.4 −103 686
08.01 982 589 911 373 866 515 34 466 30 184 4 282 64 650 7.3 6.4 0.9 −60 368
08.02 211 810 193 935 184 686 7 850 5 895 1 955 13 745 7.7 5.8 1.9 −11 790
08.03 121 201 110 757 103 905 6 344 7 111 −767 13 455 10.9 12.3 −1.3 −14 222
08.04 1 505 714 1 389 755 1 285 749 80 712 33 072 47 640 113 784 11.2 4.6 6.6 −66 144
Fuente: Estimaciones del CONAPO.

Migración intrametropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, CVE_ZM, MC, CF, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2020 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intrametropolitana.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intrametropolitana.RDS"))

Migrantes <- svytable(~CVE_MUN_RES + CVE_MUN, design = MC)

Matrices por zonas metropolitanas

load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intramunicipal 2020.RData"))

MR <- NULL
for(i in 1:length(zm)){
tabla <- ZM_2020 %>%
          select(CVE_ZM, CVE_MUN) %>%
           filter(CVE_ZM %in% zm[i]) %>%
            pull(CVE_MUN)

MR[[paste0(zm[i])]] <- Migrantes %>%
                        as.data.frame() %>%
                         tibble::rownames_to_column(var = "CVE_MUN") %>%
                          mutate_if(is.numeric, as.numeric) %>%
                           select(CVE_MUN, all_of(tabla)) %>%
                            filter(CVE_MUN %in% tabla)
}

# Se guardan en un objeto de R 
saveRDS(MR, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2020.RDS"))

# Se genera un Excel con todas las matrices por ZM
wb <- createWorkbook()
for(i in 1:length(zm)){
addWorksheet(wb, paste0(zm[i]))
writeData(wb, i, MR[[paste0(zm[i])]] %>% as.data.frame())
saveWorkbook(wb, 
              file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2020.xlsx"), 
               overwrite = TRUE)
}

Matriz de migración reciente hace 5 años en la Zona Metropolitana de Cuernavaca, 2015 - 2020

Matriz de migración reciente a nivel intramunicipal
Zona Metropolitana de Cuernavaca
CVE_MUN 017007 017008 017009 017011 017018 017020 017028 017029 017034 017035
017007 320555 469 110 2908 1113 185 290 218 92 30
017008 3949 82835 58 2509 967 66 785 179 11 60
017009 972 29 19483 103 57 3 25 14 0 3
017011 4017 857 26 180659 540 348 120 448 0 54
017018 1865 425 0 877 102261 54 509 34 0 0
017020 494 55 12 536 124 46513 72 359 0 0
017028 918 551 18 334 1108 50 57135 72 0 0
017029 565 0 28 725 104 117 159 90266 0 0
017034 48 2 0 4 18 0 21 0 10065 2
017035 60 4 0 6 11 0 46 2 5 25030
Fuente: Estimaciones del CONAPO.

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
MR <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matrices de MR5a a nivel intramunicipal por ZM2020.RDS"))

Residentes <- lapply(1:length(zm), function(x){
                                     MR[[x]] %>% 
                                      as.data.frame() %>%
                                       melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                        mutate_at(vars(3), as.numeric) %>%
                                         filter(CVE_MUN == CVE_MUN_RES)  %>%
                                          summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                           mutate(CVE_ZM = !!paste0(zm[x])) 
}
)

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

Inmigrantes <- lapply(1:length(zm), function(x){
                                      MR[[x]] %>% 
                                       as.data.frame() %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                            mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################
Emigrantes <- lapply(1:length(zm), function(x){
                                    MR[[x]] %>% 
                                     tibble::column_to_rownames(var = "CVE_MUN") %>%
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_RES)  %>%
                                            summarize(Emigrantes=  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)


tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intrametropolitano) 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intrametropolitano) 2020.RData"))
Indicadores de migración reciente
Zonas Intrametropolitano
CVE_ZM Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 1 137 351 1 041 779 965 610 8 133 8 133 0 16 266 1.49 1.49 0.0 −16 266
02.01 440 624 408 720 376 054 0 0 0 0 0.00 0.00 0.0 0
02.02 1 042 395 974 962 929 519 0 0 0 0 0.00 0.00 0.0 0
02.03 2 036 832 1 881 918 1 647 760 4 193 4 193 0 8 386 0.43 0.43 0.0 −8 386
03.01 290 063 270 823 249 997 0 0 0 0 0.00 0.00 0.0 0
03.02 350 193 316 916 260 221 0 0 0 0 0.00 0.00 0.0 0
04.01 293 199 271 217 257 197 0 0 0 0 0.00 0.00 0.0 0
05.01 1 369 966 1 249 820 1 199 403 12 933 12 933 0 25 866 1.97 1.97 0.0 −25 866
05.02 374 001 339 271 331 883 1 087 1 087 0 2 174 0.61 0.61 0.0 −2 174
05.03 207 994 189 033 177 624 323 323 0 646 0.33 0.33 0.0 −646
05.04 1 028 156 936 122 868 898 8 015 8 015 0 16 030 1.63 1.63 0.0 −16 030
05.05 106 988 97 708 95 720 234 234 0 468 0.46 0.46 0.0 −468
06.01 326 478 304 710 269 821 7 148 7 148 0 14 296 4.53 4.53 0.0 −14 296
06.02 143 572 131 524 121 925 434 434 0 868 0.63 0.63 0.0 −868
07.01 397 226 359 067 337 555 695 695 0 1 390 0.37 0.37 0.0 −1 390
07.02 846 364 773 479 741 298 9 541 9 541 0 19 082 2.36 2.36 0.0 −19 082
08.01 982 589 911 373 866 515 1 151 1 151 0 2 302 0.24 0.24 0.0 −2 302
08.02 211 810 193 935 184 686 899 899 0 1 798 0.89 0.89 0.0 −1 798
08.03 121 201 110 757 103 905 134 134 0 268 0.23 0.23 0.0 −268
08.04 1 505 714 1 389 755 1 285 749 0 0 0 0 0.00 0.00 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermetropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       select(CVE_ENT, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES, CVE_ZM, MC, CF, CVE_ZM_RES, M, EDAD, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_RES5A_ZM_2020 = ifelse(is.na(.$CVE_ZM_RES), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_RES ~ 'Pertenecen a la Zona Metropolitana', #Residentes
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_RES ~ "Pertenecen a la Zona Metropolitana", #Migrantes que residen en la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_RES ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residen en otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '1' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian fuera de la zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Migrantes que residian dentro de una zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_RES & .$I_ZM_2020 %in% '0' & .$I_RES5A_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Migrantes que no residen en la zona metropolitana
                                )) %>%
         filter(EDAD >= 5 & EDAD <= 130) %>%
          filter(CVE_MUN_RES %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/MC_intermetropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 5 años y más ###############################
Pob.5ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 5 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.5ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Matriz de migracion reciente a nivel intermunicipal 2020.RData"))

ZM <- lapply(1:length(zm), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% zm[x])  %>% 
                      pull(CVE_MUN)
})


Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
}
)

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_RES") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_RES)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)


tabla <- Pob.Total %>%
          left_join(., Pob.5ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.5ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intermetropolitano) 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/01_Migracion reciente/Indicadores de MR5a por ZM 2020 (Intermetropolitano) 2020.RData"))
Indicadores de migración reciente
Zonas Intermetropolitano
CVE_ZM Pob.Total Pob.5ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 1 137 351 1 041 779 0 56 439 23 434 33 005 79 873 10.4 4.3 6.1 −46 868
02.01 440 624 408 720 0 24 607 15 129 9 478 39 736 11.6 7.1 4.5 −30 258
02.02 1 042 395 974 962 0 31 520 20 829 10 691 52 349 6.2 4.1 2.1 −41 658
02.03 2 036 832 1 881 918 0 165 157 61 160 103 997 226 317 16.9 6.2 10.6 −122 320
03.01 290 063 270 823 0 17 969 11 442 6 527 29 411 12.8 8.2 4.7 −22 884
03.02 350 193 316 916 0 45 338 18 730 26 608 64 068 27.2 11.2 16.0 −37 460
04.01 293 199 271 217 0 12 224 17 211 −4 987 29 435 8.7 12.2 −3.5 −34 422
05.01 1 369 966 1 249 820 0 27 956 31 191 −3 235 59 147 4.3 4.8 −0.5 −62 382
05.02 374 001 339 271 0 5 028 10 975 −5 947 16 003 2.8 6.2 −3.3 −21 950
05.03 207 994 189 033 0 7 877 5 808 2 069 13 685 7.9 5.9 2.1 −11 616
05.04 1 028 156 936 122 0 42 737 21 305 21 432 64 042 8.7 4.3 4.4 −42 610
05.05 106 988 97 708 0 1 285 2 462 −1 177 3 747 2.5 4.8 −2.3 −4 924
06.01 326 478 304 710 0 22 822 16 349 6 473 39 171 14.5 10.4 4.1 −32 698
06.02 143 572 131 524 0 8 076 8 521 −445 16 597 11.7 12.4 −0.6 −17 042
07.01 397 226 359 067 0 10 851 25 002 −14 151 35 853 5.7 13.2 −7.5 −50 004
07.02 846 364 773 479 0 20 263 42 302 −22 039 62 565 5.0 10.4 −5.4 −84 604
08.01 982 589 911 373 0 33 315 29 033 4 282 62 348 7.0 6.1 0.9 −58 066
08.02 211 810 193 935 0 6 951 4 996 1 955 11 947 6.9 4.9 1.9 −9 992
08.03 121 201 110 757 0 6 210 6 977 −767 13 187 10.7 12.0 −1.3 −13 954
08.04 1 505 714 1 389 755 0 80 712 33 072 47 640 113 784 11.2 4.6 6.6 −66 144
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
extrafont 0.19 CRAN (R 4.3.0)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
showtext 0.9-6 CRAN (R 4.3.1)
showtextdb 3.0 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
sysfonts 0.8.8 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.